package com.williams.smart_freezer_williams

import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.EventChannel
import java.util.*
import kotlin.concurrent.timerTask


class LCTySmartHomeTool(var activity: Activity, messenger: BinaryMessenger):EventChannel.StreamHandler {
    private var channel: EventChannel
    private var index = 0
    private var events: EventChannel.EventSink? = null

    init {
        channel = EventChannel(messenger, "ty_smart_home_event")
        channel.setStreamHandler(this)

        //创建通知中心,设置监听的方法
//        startTimer()

        var localBroadcastManager = LocalBroadcastManager.getInstance(activity)
        val intentFilter = IntentFilter("com.example.wifi")
        // 注册广播, 配网成功回调
        localBroadcastManager.registerReceiver(object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                if (intent != null) {
                    activity.runOnUiThread {
                        events?.success(intent.getStringExtra("result"))
                    }
                }
            }
        }, intentFilter)

        val dpInfoStr = IntentFilter("com.example.dpInfoStr")
        // 注册广播, dp数据更新回调
        localBroadcastManager.registerReceiver(object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                if (intent != null) {
                    activity.runOnUiThread {

                        val temp = intent.getStringExtra("temp") as String
                        val humi = intent.getStringExtra("humi") as String
                        val devId = intent.getStringExtra("devId") as String

                        val passInfo = mapOf("temp" to temp, "humi" to humi, "devId" to devId)
                        events?.success(passInfo)
                    }
                }
            }
        }, dpInfoStr)

    }


    fun startTimer() {
        var timer = Timer().schedule(timerTask {
            index++
            var map = mapOf("name" to "laomeng${index}",
                    "age" to "${index}"
            )
            activity.runOnUiThread {
                events?.success(map)
            }

        }, 0, 1000)

    }

    override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
        this.events = events
    }

    override fun onCancel(arguments: Any?) {
        this.events = null
    }
}